package com.example.splash.font

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.text.TextPaint
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import androidx.appcompat.widget.AppCompatSeekBar

/**
 * 带文本的滑杆
 * Created by ChenRui on 2017/10/13 0013 12:50.
 */
open class RaeSeekBar : AppCompatSeekBar {


    private val mTickMarkTitlePaint: Paint = TextPaint(Paint.ANTI_ALIAS_FLAG)
    private var mThumbWidth = 0
    private var mThumbHeight = 0
    private val mRect = Rect()

    private var mLineHeight = getSize(8f) // 刻度高度

    private var mMargin =getSize(12f)

    private var mScaleSize = getSize(1F)

    private val TAG = "RaeSeekBar"


    constructor(context: Context?) : super(context!!) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(
        context!!, attrs
    ) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!, attrs, defStyleAttr
    ) {
        init()
    }


    private fun init() {
        mTickMarkTitlePaint.color = Color.parseColor("#B9B9B9")
        progressDrawable = ColorDrawable(Color.TRANSPARENT)
    }

    override fun onDraw(canvas: Canvas) {
        val max = max
        val width = width
        val height = height
        val h2 = height / 2
        // 画刻度背景
        mRect.left = 0
        mRect.right = width
        mRect.top = h2 - mScaleSize
        mRect.bottom = mRect.top + mScaleSize
        canvas.drawRect(mRect, mTickMarkTitlePaint)

        //刻度
        val cw = mRect.right - mRect.left  - 2*mMargin // 总画线的长度 = 右边坐标 - 左边坐标
        val pos = cw / max
        Log.d(TAG, "onDraw: cw:$cw")
        for (i in 0..max) {
            // 画分割线
            val offset = (i * pos) + mMargin
            mRect.top =h2 - mLineHeight
            mRect.bottom = h2
            mRect.left = offset
            mRect.right =offset + mScaleSize
            canvas.drawRect(mRect, mTickMarkTitlePaint)
        }
        super.onDraw(canvas)
    }

    @Synchronized
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mThumbWidth = thumb.intrinsicWidth
        mThumbHeight = thumb.intrinsicHeight
        val wm = MeasureSpec.getMode(widthMeasureSpec)
        val hm = MeasureSpec.getMode(heightMeasureSpec)
        val w = measuredWidth
        val h = measuredHeight
        setMeasuredDimension(MeasureSpec.makeMeasureSpec(w, wm), MeasureSpec.makeMeasureSpec(h, hm))
    }

    private fun getSize(size: Float): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            size,
            resources.displayMetrics
        ).toInt()
    }

}